import React from 'react'
import './my-fuli.css'
import LocalStorageService from "../../utils/LocalStorageService";
import {Icon, Modal, Tabs, Toast} from "antd-mobile";
import TabWithCustomUnderline from "../../layouts/TabWithCustomUnderline/TabWithCustomUnderline";
import {changePiece, getFuliRank, getMyFuli, getUserDetailReq, sellPiece} from "../../apis/goApis";
import {log} from "../../utils/commonfunc";
import Countdown from "../plan-detail/Countdown/Countdown";
import moment from "moment";
import numberPopSrc from '../../res/images/web/together/number pop备份 4@2x.png'
import CustomBotton from "../../shared-components/CustomButton/CustomBotton";
import pieceSelectedBoarderSrc from "../../res/images/web/together/碎片-选中@2x.png"
import CountDisplay from "../game-room/components/Main/chat-room/GiftPopup/GiftCount/CountDisplay/CountDisplay";
import coinSrc from "../../res/images/web/shared/coin-o.png"
import defaultAvartarSrc from "../../res/images/web/together/我的碎片@2x.png";
import {withRouter,} from 'react-router-dom'
import ruleSrc from '../../res/images/web/together/rule@2x.png'
import FuliRuleModal from "../fuli/RuleModal";
import Digit from "../plan-detail/Countdown/Digit/Digit";
class MyFuli extends React.Component {
    constructor(props) {
        super(props)
        this.uid = LocalStorageService.get('userid')
        this.pieceListContainer = React.createRef()
        this.state = {
            myFuli: [],
            fuliIndex: 0,
            expire: 0,
            imgWidth: 0,
            imgHeight: 0,
            pieceIndex: 0,
            pieceCount: 0,
            modalSell: false,
            modalChange: false,
            rank: [],
            myRank: {
                count: 0,
                rank: 0,
                price: 0,
            },
            p: 0,
            userDetail: {
                nickname: '',
                iconSrc: '',
            },
            modalRule: false,
        }
    }

    componentDidMount() {
        this.getUserDetail()
            .then(() => this.getMyFuli())
            .then(() => this.getRank())
    }

    getUserDetail() {
        return getUserDetailReq({
            uid: this.uid,
        }).then(res => {
            this.setState({
                userDetail: {
                    nickname: res.data.ok.Nickname,
                    iconSrc: res.data.ok.Iconurl,
                }
            })
        })
    }

    getMyFuli() {
        return getMyFuli({
            Uid: this.uid,
        }).then(resp => {
            log("resp", resp)
            this.setState({
                myFuli: resp.data.ok,
                expire: resp.data.expire,
            })
        })
    }

    getRank() {
        return getFuliRank({
            P: this.state.p,
            Uid: this.uid,
        }).then(res => {
            // blockcount: 257
            // ok: (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]
            // price: 5726
            // rank: 2
            this.setState({
                rank: res.data.ok,
                myRank: {
                    rank: res.data.rank,
                    count: res.data.blockcount,
                    price: res.data.price,
                }
            })

        })
    }

    switchFuliIndex(step) {
        let start = this.state.fuliIndex
        let end = start + step
        if (end < 0 || end > 2) {
            return
        }
        this.setState({
            fuliIndex: end,
            pieceIndex: 0,
        })
        this.pieceListContainer.scrollLeft = 0
    }

    sell(piece) {
        log(piece)
        let owned = piece.Count
        let count = this.state.pieceCount
        // Uid    string `binding:"required"`
        // Fuliid int    `binding:"required"` //福利物品号
        // Number int    `binding:"required"` //碎片号
        // Count  int    `binding:"required"` //数量
        if (count === 0) {
            Toast.fail('碎片数量必须大于0', 0.5)
            return
        }
        if (owned === 0 || (owned < count)) {
            Toast.fail('碎片数量不够', 0.5)
            return
        }
        sellPiece({
            Uid: this.uid,
            Fuliid: this.state.myFuli[this.state.fuliIndex].Fuliid,
            Number: piece.Number,
            Count: count,
        }).then(res => {
            if (res.data.ok === 1) {
                Toast.success('出售成功', 0.5)
                setTimeout(() => this.getMyFuli(), 500)
            }
        })
    }

    change(piece) {
        log(piece)
    }

    onPieceChange() {
        // this.onPieceButtonClick('change')
        let fuli = this.state.myFuli[this.state.fuliIndex]
        let enough = fuli.Value.every(f => f.Count > 0)
        if (enough) {
            changePiece({
                Uid: this.uid,
                Fuliid: fuli.Fuliid,
            }).then(res => {
                if (res.data.ok === 1) {
                    this.setState({
                        modalChange: true,
                    })
                }
            }).then(() => this.getMyFuli())
        } else {
            Toast.fail('无法兑换', 0.5)
        }
    }

    render() {
        const myFuli = this.state.myFuli
        const index = this.state.fuliIndex
        const pieceData = myFuli[index]
        let pieceTemplate
        if (pieceData) {
            let pieceDataList = pieceData.Value
            const now = moment(new Date())
            const days = moment(this.state.expire * 1000).diff(now, 'day')
            pieceTemplate = <div>
                <div
                    className='flex-space-between-align-center pd-l-r-16px'
                    style={{background: '#F1F1F1', height: 40,}}
                >
                    <div className='flex-align-center'>
                        <span className='gray-text mg-r-6px' style={{fontSize: '10px',}}>碎片有效期</span>
                        <Digit
                            now={days}
                            textStyle={{
                                fontSize: '12px',
                                fontWeight: '500',
                                color: '#333333',
                            }}
                            textContainerStyle={{
                                width: 24,
                                height: 24,
                            }}
                            isLast={true}
                        />
                        <span className='gray-text mg-r-4px mg-l-4px' style={{fontSize: '10px',}}>天</span>
                        <Countdown
                            begin={parseInt(moment(new Date()).format('X'))}
                            end={this.state.expire}
                            textStyle={{
                                fontSize: '12px',
                                fontWeight: '500',
                                color: '#333333',
                            }}
                            textContainerStyle={{
                                width: 24,
                                height: 24,
                            }}
                            oneday={true}
                        />
                    </div>
                    <div className='flex-align-center' onClick={() => this.props.history.push('./my-fuli-record')}>
                        <span className='gray-text mg-r-4px' style={{fontSize: '10px',}}>出售/兑换记录</span>
                        <Icon type='right' size="xxs" />
                    </div>
                </div>
                <div className='pd-16-px' style={{width: '100%', height: '100%',}}>
                    <div style={{position: 'relative',}}>
                        <img
                            src={pieceDataList[0].Url[3]}
                            alt=''
                            style={{width: '100%',}}
                            onLoad={e => {
                                let target = e.target
                                this.setState({
                                    imgWidth: target.width,
                                    imgHeight: target.height,
                                })
                            }}
                        />
                        {pieceDataList.map((pieceData, index) => {
                            let enough = pieceData.Count > 0
                            if (enough) {
                                const urls = pieceData.Url
                                const url = urls[1]

                                let w = this.state.imgWidth / 3
                                let h = this.state.imgHeight / 2
                                let width = w
                                let height = h
                                let gapW = w / 3
                                let gapH = h / 3
                                let top = '0px'
                                let left

                                if (index === 0) {
                                    width += gapW
                                    left = '0px'
                                }
                                if (index === 1) {
                                    left = w
                                    height += gapH
                                }
                                if (index === 2) {
                                    left = 2 * w - gapW
                                    width += gapW
                                }
                                if (index === 3) {
                                    left = 0
                                    top = h - gapH
                                    height += gapH
                                }
                                if (index === 4) {
                                    left = w - gapW
                                    top = h
                                    width = w + gapW
                                }
                                if (index === 5) {
                                    top = h - gapH
                                    left = 2 * w - gapW
                                    width = w + gapW
                                    height = w + gapH
                                }

                                return <img key={index} src={url}
                                            style={{width, height, top: top, left: left, position: 'absolute',}}
                                            alt=''/>
                            }
                        })}
                    </div>
                </div>
                <div className='flex-align-center' style={{overflowX: 'scroll',}}
                     ref={el => this.pieceListContainer = el}>
                    {pieceDataList.map((pieceData, index) => {
                        return <div key={index} className='pd-16-px text-align-center'
                                    onClick={() => this.setState({pieceIndex: index,})}>
                            <div style={{
                                width: 56,
                                height: 56,
                                background: `no-repeat url(${pieceData.Url[2]}) 50% 50%/cover`,
                                borderRadius: '4px',
                                position: 'relative',
                            }} className='mg-b-8px'>
                                <div style={{
                                    position: 'absolute',
                                    width: 20,
                                    height: 20,
                                    right: -10,
                                    top: -10,
                                    background: `no-repeat url(${numberPopSrc}) 50% 50%/cover`,
                                    textAlign: 'center',
                                    zIndex: 2,
                                }}>
                                    <span style={{
                                        fontSize: '10px',
                                        lineHeight: '20px',
                                        color: '#fff'
                                    }}>{pieceData.Count}</span>
                                </div>
                                {index === this.state.pieceIndex ?
                                    <img style={{position: 'absolute', top: 0, left: 0, width: '58px', height: '58px',}}
                                         src={pieceSelectedBoarderSrc} alt=''/> : null}
                            </div>
                            <span>{index + 1}号碎片</span>
                        </div>
                    })}
                </div>

                <div style={{background: '#fff', padding: '16px', textAlign: 'center',}}>
                    <p>- 当前福利 -</p>
                    <div className='flex-space-between-align-center'>

                        <div
                            style={{
                                background: index === 0 ? '#F1F1F1' : '#36C8B9',
                                width: 44,
                                height: 44,
                                borderRadius: '50%',
                            }}
                            className='flex-center-align-center'
                            onClick={() => this.switchFuliIndex(-1)}
                        >
                            <Icon type="left" size='xs' style={{color: index === 0 ? `#A4A4A4` : '#fff',}}/>
                        </div>

                        <div className='flex-align-center'>
                            <span className='fuli-item-lv-mark'>
                                Lv.{this.state.fuliIndex + 1}
                            </span>
                            <span
                                style={{
                                    fontSize: '20px',
                                    fontWeight: '600',
                                    color: '#333333',
                                    lineHeight: '20px',
                                }}
                            >
                                {pieceData.Quota}元{pieceData.Name}
                            </span>
                        </div>

                        <div
                            style={{
                                background: index === 2 ? '#F1F1F1' : '#36C8B9',
                                width: 44,
                                height: 44,
                                borderRadius: '50%',
                            }}
                            className='flex-center-align-center'
                            onClick={() => this.switchFuliIndex(1)}
                        >
                            <Icon type="right" size='xs' style={{color: index === 2 ? '#A4A4A4' : '#fff',}}/>
                        </div>
                    </div>
                    <span className='gray-text'>已有10人成功兑换</span>
                </div>
                <div className='flex-space-between-align-center' style={{padding: '24px 16px', background: '#fff',}}>
                    <CustomBotton
                        extrastyle={{marginRight: '8px',}}
                        bg='#FFA500'
                        // onClick={() => this.onPieceSell()}
                        onClick={() => this.setState({modalSell: true,})}
                    >
                        出售
                    </CustomBotton>
                    <CustomBotton
                        bg='#FFA500'
                        onClick={() => this.onPieceChange()}
                    >
                        兑换
                    </CustomBotton>
                </div>
            </div>
        }

        let sellModal = null

        if (pieceData) {
            const curPieceData = pieceData.Value[this.state.pieceIndex]

            sellModal = <Modal
                visible={this.state.modalSell}
                onClose={() => this.setState({modalSell: false,})}
                maskClosable
                transparent
                className='no-padding-modal'
            >
                <img src={curPieceData.Url[2]} alt="" style={{
                    width: 56,
                    height: 56,
                    boxShadow: '0px 2px 3px 0px rgba(0, 0, 0, 0.06)',
                    marginBottom: '12px',
                }}/>
                <p>
                    {this.state.pieceIndex + 1}号碎片
                </p>
                <div className='flex-center-align-center mg-b-8px'>
                    <img src={coinSrc} alt=''/>
                    <span>{curPieceData.Price}</span>
                </div>
                <div className='flex-center-align-center mg-b-8px'>
                    <CountDisplay
                        total={this.state.pieceCount}
                        changeTotal={(i) => {
                            let count = this.state.pieceCount + i
                            this.setState({
                                pieceCount: count,
                            })
                        }}
                    />
                </div>
                <span>
                    拥有：{curPieceData.Count}
                </span>
                <div className='flex-space-between-align-center mg-t-8px'>
                    <div
                        className='flex-1'
                        style={{
                            borderTop: '1px solid #F8F8F8',
                            padding: '14px',
                            marginRight: '-15px',
                            borderRight: '1px solid #F8F8F8',
                        }}
                        onClick={() => this.setState({modalSell: false, pieceCount: 0,})}
                    >
                        取消
                    </div>
                    <div
                        className='flex-1'
                        style={{borderTop: '1px solid #F8F8F8', padding: '14px',}}
                        onClick={() => this.sell(curPieceData)}
                    >
                        出售
                    </div>
                </div>
            </Modal>
        }

        const rankTemplate = <div className='pd-16-px'>
            <div className='flex-space-between mg-b-4px' style={{padding: '0 12px', fontSize: '10px',}}>
                <span className='gray-text flex-2'>名次</span>
                <span className='gray-text flex-1'>碎片数量</span>
                <span className='gray-text flex-1' style={{textAlign: 'right',}}>价值</span>
            </div>
            <div className='bg-white'>
                {this.state.rank.map((user, index) => {
                    const avatarSrc = user?.Iconurl || defaultAvartarSrc
                    return <div key={index} className='flex-space-between-align-center heat-rank pd-l-r-12px'>
                        <div className='flex-align-center heat-rank-item flex-2'>
                                <span className='heat-rank-item-rank'>
                                    {index + 1}
                                </span>
                            <img alt='' src={avatarSrc}
                                 style={{width: 28, height: 28, borderRadius: '50%', marginRight: '20px',}}/>
                            <span>{user.Nickname}</span>
                        </div>
                        <span className='flex-1 text-align-right'>
                            {user.Count}
                        </span>
                        <span className='heat-rank-item-heat flex-1 text-align-right'>
                            {user.Price}
                        </span>
                    </div>
                })}
            </div>

        </div>

        const changeModal = <Modal
            visible={this.state.modalChange}
            transparent
            onClose={() => this.setState({modalChange: false,})}
            title="礼物兑换"
            footer={[{text: '好的', onPress: () => this.setState({modalChange: false,})},]}
        >
            <p>客服审核（通常15个工作日内）通过后，会将奖金发送至客户端绑定的手机号码对应的支付宝账号，请耐心等候，如有疑问，请及时联系微信客服</p>
        </Modal>
        return <>
            {sellModal}
            {changeModal}
            <FuliRuleModal
                visible={this.state.modalRule}
                onClose={() => this.setState({modalRule: false,})}
            />
            <Icon type='left' size="lg" onClick={() => this.props.history.goBack()} color='#333' style={{position: 'absolute', top: 4, left: '', zIndex: 100,}}/>
            <div
                className='flex-align-center'
                style={{position: 'absolute', top: '15px', right: '12px', zIndex: 100,}}
                onClick={() => this.setState({modalRule: true,})}
            >
                <img alt="" src={ruleSrc} style={{width: 13, height: 13, marginRight: '4px',}}/>
                <span style={{color: '#FFA500',}}>规则</span>
            </div>
            <TabWithCustomUnderline
                tabs={[
                    {title: '我的碎片',},
                    {title: '碎片排行',},
                ]}
                tabBarUnderlineStyle={{
                    width: '40%',
                    borderRadius: '0',
                    background: '#36C8B9',
                }}
                prefixCls='width-50-tab'
                tabBarBackgroundColor='#ffffff'
            >
                <div>
                    {pieceTemplate}
                </div>
                <div style={{height: window.innerHeight - 43.5, position: 'relative',}}>
                    {rankTemplate}
                    <div style={{position: 'absolute', bottom: 0, left: 0, width: '100%', padding: '10px 28px', background: 'rgba(0, 0, 0, 0.8)',}} className='flex-space-between-align-center'>
                        <div className='flex-align-center flex-2'>
                            <span className='heat-rank-item-rank' style={{color: '#FFC863'}}>
                                {this.state.myRank.rank + 1}
                            </span>
                            <img
                                alt=''
                                src={this.state.userDetail.iconSrc}
                                style={{width: 28, height: 28, borderRadius: '50%', marginRight: '20px',}}
                            />
                            <span style={{color: '#fff',}}>{this.state.userDetail.nickname}</span>
                        </div>
                        <span className='flex-1 text-align-right' style={{color: '#fff',}}>
                            {this.state.myRank.count}
                        </span>
                        <span className='heat-rank-item-heat flex-1 text-align-right' style={{color: '#fff',}}>
                            {this.state.myRank.price}
                        </span>
                    </div>
                </div>

            </TabWithCustomUnderline>
        </>
    }
}

export default withRouter(MyFuli)